<?php
class Story_model extends CI_Model {

	function __construct() {
        parent::__construct();
    }
	
	function get_story_comment_num( $story_id ) {
		// 获取故事的评论数
		$sql = "
			SELECT COUNT(*) AS num
			FROM comment
			WHERE comment.story_id = '{$story_id}'
		";
		
		$query = $this->db->query( $sql );
		$comment_num = $query->row()->num;
		return $comment_num;
	}
	
	function get_likes_num($story_id, $type = 1) {
		// 获取故事的喜欢与不喜欢数
		// $story_id 故事id
		// $type 1=喜欢 2=不喜欢
		
		$sql = "
			SELECT COUNT(*) AS num
			FROM vote
			WHERE vote.story_id='{$story_id}'
				AND 	vote.vote_type = '{$type}'
				AND vote.vote_for = '0'
		";
		
		$query = $this->db->query( $sql );
		return  $query->row()->num;
	}
	
	function get_comment_likes_num( $comment_id ) {
		$sql = "
			SELECT COUNT(*) AS num
			FROM vote
			WHERE vote.story_id='{$comment_id}'
				AND 	vote.vote_type = '1'
				AND vote.vote_for = '1'
		";
		$query = $this->db->query( $sql );
		return  $query->row()->num;
	}
	
	function check_user_vote_status( $user_id, $story_id, $type = 0 ) {
		// 检查$user_id关于$story_id的投票状态	
		// $type 0=故事投票 1=评论投票
		// return 0= 未投票 1=喜欢 2=不喜欢
		
		$flag = $this->vote_or_not( $user_id, $story_id );
		// echo $flag;
		if( $flag == 1 ) {	// 投票了
			$sql = "
				SELECT	vote.vote_type AS flag
				FROM vote
				WHERE  vote.story_id = '{$story_id}'
					AND vote.user_id = '{$user_id}'
					AND vote.vote_for = '{$type}'
			";
			$query = $this->db->query( $sql );
			return $query->row()->flag;
		}
		
		return $flag;
	}
	
	
	function vote_or_not( $uid, $story_id ) {
		// 是否投票
		// return 1=已经投票 0=没有投票
		$sql = "
			SELECT COUNT(*) AS flag
			FROM vote
			WHERE vote.user_id = '{$uid}'
				AND vote.story_id = '{$story_id}'
		";
		$query = $this->db->query( $sql );
		return $query->row()->flag;
	}
	
	function change_user_vote_status( $uid, $story_id, $type, $vote_for = 0 ) {
		// 插入或更改投票的状态
		// $type 1=喜欢 2=不喜欢
		// 成功返回true 否则返回false
		
		$flag = $this->vote_or_not( $uid, $story_id );
		$vote_date = date('Y-m-d H:i:s');	// 投票时间
		if( $flag == 0 ) {
			$sql = "
				INSERT INTO vote( user_id, story_id, vote_type, vote_date, vote_for )
				VALUES ('{$uid}', '{$story_id}', '{$type}', '{$vote_date}', '{$vote_for}')
			";
		} else {
			$sql = "
				UPDATE vote
				SET vote_type='{$type}', vote_date='{$vote_date}'
				WHERE story_id = '{$story_id}' 
					AND user_id = '{$uid}'
			";
		}
		
	
		if( $this->db->query( $sql ) ) {
			return 1;
		} else {
			return 0;
		}
	}
	
	function is_exist_story( $story_id, $uid ) {
		// 判断布丁是否存在
		// 0=不存在 1=存在
		$sql = "
			SELECT COUNT(*) AS flag
			FROM story
			WHERE story.story_id = '{$story_id}'
				AND story.user_id = '{$uid}'
		";
		$query = $this->db->query( $sql );
		return $query->row()->flag;
	}
	
	function check_story_id( $story_id ) {
		$sql = "
			SELECT COUNT(*) AS flag
			FROM story
			WHERE story.story_id = '{$story_id}'
				AND story.story_type='0'
		";
		$query = $this->db->query( $sql );
		return $query->row()->flag;
	}
	
	function get_story_type( $story_id, $uid ) {	
		// 包含16,17
		// 获取故事的类型
		// 0=已发表 1=草稿 2=不存在该故事
		$flag = $this->is_exist_story( $story_id, $uid );
		if( $flag == 0 ) {
			return 2;
		} else {
			
			$sql = "
				SELECT story.story_type AS type
				FROM story
				WHERE	story.story_id = '{$story_id}'
			";
			
			$query = $this->$db->query( $sql );
			return $query->row()->type;
		}
	}
	
	function get_story( $story_id ) {
		// 获取故事信息
		// 故事的标题、内容等
		$sql = "
			SELECT *
			FROM story
			WHERE story.story_id = '{$story_id}'
		";
		
		$query = $this->db->query( $sql );
		return $query->row_array();
	}
	
	
	
	function get_followed_columns( $uid ) {
		// 获得用户关注的专栏列表
		$sql = "
			SELECT	topic.topic_id AS id, topic.topic_title AS title
			FROM follow_topic, topic
			WHERE follow_topic.user_id = '{$uid}'
				AND topic.topic_id = follow_topic.topic_id
			ORDER BY topic.topic_create_date DESC
		";
		$query = $this->db->query( $sql );
		return $query->result_array();
	}
	
	function get_one_column( $topic_id ) {
		$sql = "
			SELECT topic_id AS id, topic_title AS title
			FROM topic 
			WHERE topic_id = {$topic_id}
		";
		
		$query= $this->db->query( $sql );
		return $query->row_array();
	}
	
	
	function html_select_followed_columns( $uid, $topic_id,  $type = 0 ) {
		// html用户关注的专栏列表
		$columns_list = $this->get_followed_columns( $uid );
		if( $type == -1 ) {
			$first  = array_shift( $columns_list );	
		} else {
			$first = $this->get_one_column( $topic_id );
		}
		extract( $first );
	?>
		
			<select name="column_id">
				<option value="<?=$id?>" title="<?=$title?>" selected><?=$title?></option>
	<?php
				foreach( $columns_list as $column) {
					extract( $column );
					if( $id != $first['id'] ) {
						echo "<option value='{$id}' title='{$title}'>{$title}</option>";
					}
				}
	?>
			</select>
	
	<?php
	}
	
		function add_btns_to_editor( $type ) { 
				// 根据故事类型添加按钮
			$type = mysql_real_escape_string( $type );
		?>
			<div class="form-group">
		<?php
			switch( $type ) {
				case '-1':
					echo "<div><input type='submit' class='btn btn-primary btn-sm' name='post_btn' value='发表' style='margin-right: 10px;'/>";
					echo "<input type='submit' class='btn btn-primary btn-sm' name='save_draft_btn' value='存为日记'/></div>";
					break;
				case '0':
					echo "<div><input type='submit' class='btn btn-primary btn-sm' name='edit_done_btn' value='完成修改' style='margin-right: 10px;'/>";
					echo "<input type='submit' class='btn btn-primary btn-sm' name='save_draft_btn' value='存为日记'/></div></div>";
					break;
				case '1':
					echo "<div><input type='submit' class='btn btn-primary btn-sm' name='save_draft_btn' value='存为日记' style='margin-right: 10px;'/>";
					echo "<input type='submit' class='btn btn-primary btn-sm' name='post_btn' value='发表' /></div>";
					
			}
		?>
			</div>
		<?php
		}
	
	function output_editor(  $act, $data = array() ) {
		// 打印故事的信息
		// $data=故事标题、内容等等
		extract( $data );
		// print_arr( $data );	//tbd
	?>
		<script>
		$( function() {
			$("#followed-topic").hide();
			$("#search-topic").hide();
			
			$("input[name='column_from']").click( function() {
				var v = $(this).val();
				if( v == 0 ) {
					$("#followed-topic").show();
					$("#search-topic").hide();
				} else {
					$("#followed-topic").hide();
					$("#search-topic").show();
				}
			} );
		} );
		</script>
		
		<div class="editor-wrap">
			<div class="editor-box">
					<div class="editor">
						<?php 
						$attrs = array('class' => 'form-horizontal', 'role' => 'myform', 'id'=>'write-form');
						echo form_open(base_url().'home/write?act='.$act, $attrs); 
						?>
						<div class="bding-component">
							<div class="form-group">
								<div id="error-place">
									<?php echo validation_errors(); ?>
								</div>
							</div>
							
							<div class="form-group">
								<input type="text" autocomplete="off" name="story_title" class="form-control title" placeholder="标题" value="<?=trim(set_value('story_title')) =="" ? $story_title : set_value('story_title');?>">
							</div>
							
							<div class="form-group">
								<textarea name="story_content" class="form-control" rows="3"><?=trim(set_value('story_content')) == "" ? $story_content : set_value('story_content') ?></textarea>
							</div>
							
							<div class="form-group column">
								  <label for="column_from" class="col-sm-2 control-label">专栏</label>
								   <div class="col-sm-10">
										<input type="radio" name="column_from"  value="0"> 已关注
										<input type="radio" name="column_from"  value="1">搜索
									</div>
							</div>
							
							<div class="form-group" id="followed-topic">
								  <label for="column_id" class="col-sm-2 control-label">&nbsp;</label>
								   <div class="col-sm-10">
									<?php
									$this->html_select_followed_columns( $uid, $topic_id, $story_type );
									if( $story_type !=  -1 ) { ?>
										<script>
										$( function() {
											$("#followed-topic").show();
											$("input[name='column_from']:eq(0)").attr("checked","checked");
										} );
										</script>
									<?php } else if( isset( $column ) && !empty( $column ) )  {?>
										<script>
										$( function() {
											$("#search-topic").show();
											$("input[name='column_from']:eq(1)").attr("checked","checked");
											$("#column-name").html("<?=$column?>");
										} );
										</script>
									<?php
										} else {
									?>
										<script>
										$( function() {
											// $("#followed-topic").show();
											// $("input[name='column_from']:eq(0)").attr("checked","checked");
										} );
										</script>
									<?php
										}
									?>
									</div>
							</div>
							
							<div class="form-group" id="search-topic">
								<label for="find_topic" class="col-sm-2 control-label">&nbsp;</label>
								<div class="col-sm-10">
									<input type="text" name="find_topic" autocomplete="off" value=""  class="" style="border:1px solid #ccc; padding:2px; width:200px"/><span id="column-name" class="label label-default pull-right" name="column_name"></span>
									<p><a href="#" target="_blank">创建专栏</a></p>
								</div>
							</div>
						</div>
				
						<div class="cooker-action">
							<div class="bding-edit-item">
								<input type="hidden" name="next_type" value="<?=$story_type?>" />
								<input type="hidden" name="topic_id" value="<?=$topic_id?>" />
								<input type="hidden" name="story_id" value="<?=$story_id?>"/>
							</div>
							
							<?php	
							$this->add_btns_to_editor($story_type);
							?>
						</div>
					</form>	
				</div>
			</div>
		</div>
	<?php
	}
	
	
	
	
	function html_editor( $act=0, $data=array() ) {
		// data['story_id']
		// data['uid']
		if( $act == 0 ) {	// 如果是新建
			$data['story_title'] = '';
			$data['story_content'] = '';
			$data['topic_id']  = -1;
			$data['story_id']  = -1;
			$data['story_type']  = -1;
			$this->output_editor( $act, $data );	// 输出框
		} else if( $act == 1 ) {
			$sid = $data['story_id'];
			$uid = $data['uid'];
			if( $sid == -1 ) redirect();	// tbe 跳转
			$uid = $data['uid'];	// 是否有权限编辑
			if( $this->is_exist_story( $sid, $uid ) == 0 ) {
				// redirect();	// tbe 不存在的故事，跳转
				// 可以放在外层检测
			}
			
			$s = $this->get_story( $sid );
			$data['story_title'] = $s['story_title'];
			$data['story_content'] = $s['story_content'];
			$data['topic_id']  = $s['topic_id'];
			$data['story_type'] = $s['story_type'];
			$this->output_editor( $act, $data );	// 输出
		}
	}
	
	function post_new_story( $data = array() ) {
		$s['user_id'] = mysql_real_escape_string( $data['uid'] );
		$s['story_title'] = mysql_real_escape_string( trim($data[ 'story_title' ]) );
		$s['story_content'] = mysql_real_escape_string( $data[ 'story_content' ] );
		$s['post_date'] = date( 'Y-m-d H:i:s' );
		$s['recent_edit_date'] = $s['post_date'];
		
		if( $data['column_from'] == 0 ) {
			$s['topic_id'] = mysql_real_escape_string( $data['column_id'] );
		} else {
			// tbe
		}
	
		$s['story_type'] = 0;
		if( isset( $data['post_btn'] ) ) {
			$s['story_type'] = 0;		
		} else if( isset( $data['save_draft_btn'] ) ) {
			$s['story_type'] = 1;
		}
		extract( $s );
		$sql = "
			INSERT INTO story( story_title, story_content, story_type, topic_id,  user_id, post_date, recent_edit_date )
				VALUES('{$story_title}', '{$story_content}', '{$story_type}', '{$topic_id}', '{$user_id}', '{$post_date}', '{$recent_edit_date}')
		";
		$this->db->query( $sql );
		
	}
	
	function update_saved_story( $data = array() ) {
		$s['user_id'] = mysql_real_escape_string( $data['uid'] );
		$s['story_id'] = mysql_real_escape_string( $data[ 'story_id' ] );
		$s['story_title'] = mysql_real_escape_string( trim($data[ 'story_title' ]) );
		$s['story_content'] = preg_replace("/[\r\n]/", "", mysql_real_escape_string( $data[ 'story_content' ] ) );
		$s['recent_edit_date'] =  date( 'Y-m-d H:i:s' );
		
		if( $data['column_from'] == 0 ) {
			$s['topic_id'] = mysql_real_escape_string( $data['column_id'] );
		} else if( $data['column_from'] == 1 ) {
			// tbe
		}
		extract($s);
		
		if( isset( $data['edit_done_btn'] ) ) {
			// 完成修改按钮
			$sql = "
					UPDATE story
					SET story_title = '{$story_title}',
						story_content = '{$story_content}',
						recent_edit_date = '{$recent_edit_date}',
						topic_id = '{$topic_id}'
					WHERE story_id = '{$story_id}'
				";
		
			$this->db->query( $sql );
		} else if( isset( $data['post_btn'] ) ) {
			// 发表按钮
			$sql = "
					UPDATE story
					SET story_title = '{$story_title}',
						story_content = '{$story_content}',
						recent_edit_date = '{$recent_edit_date}',
						post_date = '{$recent_edit_date}',
						topic_id = '{$topic_id}',
						story_type= '0'
					WHERE story_id = '{$story_id}'
				";
		
			$this->db->query( $sql );
		} else  if( isset( $data['save_draft_btn'] ) ) {
			// 保存草稿按钮
			$sql = "
					UPDATE story
					SET story_title = '{$story_title}',
						story_content = '{$story_content}',
						recent_edit_date = '{$recent_edit_date}',
						topic_id = '{$topic_id}',
						story_type= '1'
					WHERE story_id = '{$story_id}'
				";
		
			$this->db->query( $sql );
		}
		
	}
	
	function post_story( $act, $data = array() ) {
		// 处理发表故事的信息
		if( $act == 0 ) {
			return $this->post_new_story( $data );
		} else if( $act == 1 ) {
			return $this->update_saved_story( $data );
		} 
	}
	
	function html_complete_story($uid, $item) {	// tbe
			// 显示每条的订阅信息
			extract( $item );
			$author_id = $user_id;	// 提取作者
			$post_date = substr( $post_date, 0, 16 );
			$story_content = stripslashes( $story_content );
			$story_link = "";
		?>
			<div class="bding-item" id="story-<?=$story_id?>">
				<div class="bding-desc">
					<div class="bding-content">
						<div>
							<h3><?=$story_title?></h3>
							<div class="date-count"><span><?=$post_date?></span><span>阅读(<?=$view_count?>)</span></div>
							<p><?=$story_content?></p>
						</div>
					</div>
					<?php
					$this->Story_model-> html_story_interact( $story_id, $uid, $author_id);
					?>
				</div>
			</div>
			<script>
			$( function() {
				// 投票按钮的实现	
				var likeBtns = $("a[action='like-story']");
				$.each( likeBtns, function(idx, elem) {
					var marked = $(elem).attr('marked');
					var storyId = $(elem).attr('rel');
					if( marked == 1) {
						$(elem).addClass('disable');
					}
					
					$(elem).click( function() {
						marked = $(elem).attr('marked');	
						if( marked == 0 ) {
							// 更改本按钮
							$.ajax({
								url: "<?=base_url()?>ajax/vote_story?story_id="+storyId+"&type=1",
								dataType: 'json',
								success: function( data ) {
									if( parseInt(data.status) == 1) {
										$("#like-story-"+storyId).attr('marked', 1);
										$("#like-story-"+storyId).addClass('disable');
										
										$("#unlike-story-"+storyId).attr('marked', 0);
										$("#unlike-story-"+storyId).removeClass('disable');
										
										$("#likes-sta-"+storyId).text( '('+ data.likes +')' );
										$("#unlikes-sta-"+storyId).text('('+ data.unlikes+')' );
									}
								},
								beforeSend: function() {
									$('#loading').show();
								},
								complete: function() {
									$('#loading').hide();
								}
							});
							
						}
					});
					
				} );
				
				var unlikeBtns = $('a[action="unlike-story"]');
				$.each( unlikeBtns, function(idx, elem) {
					var marked = $(elem).attr('marked');	// 1投票不喜欢
					var storyId = $(elem).attr('rel');
					var type = $(elem).attr('data');
					if( marked == 1 ) {
						$(elem).addClass('disable');
					}
					
					$(elem).click( function() {
						marked = $(elem).attr('marked');
						if( marked == 0 ) {
							$.ajax({
								url: "<?=base_url()?>ajax/vote_story?story_id="+storyId+"&type=2",
								dataType: 'json',
								success: function( data ) {
									if( parseInt(data.status) == 1) {
										$("#unlike-story-"+storyId).attr('marked', 1);
										$("#unlike-story-"+storyId).addClass('disable');
										
										$("#like-story-"+storyId).attr('marked', 0);
										$("#like-story-"+storyId).removeClass('disable');
										
										$("#likes-sta-"+storyId).text( '('+ data.likes +')' );
										$("#unlikes-sta-"+storyId).text('('+ data.unlikes+')' );
										// alert( 'hello');
									}
								},
								beforeSend: function() {
									$('#loading').show();
								},
								complete: function() {
									$('#loading').hide();
								}
							});
						}
					});
				
				} );
			});
			</script>
			
		<?php
		}
		
		function update_view_count( $story_id, $uid ) {
			// 更新浏览的次数
			$flag	= $this->is_exist_story( $story_id, $uid );	// $story_id的作者是$uid
			if( $flag == 0 ) {
				$sql = "UPDATE story SET view_count = view_count + 1 WHERE story_id = '{$story_id}'";
				if( $this->db->query( $sql ) ) 
					return true;
				return false;
			}
		}
		
		
		function insert_update_eat_history( $uid, $story_id ) {
			// 插入或者更新一条阅读信息
			// uid 用户的id
			// story_id 故事的id
			$sql = "
				SELECT COUNT(*) AS flag
				FROM history
				WHERE 
					story_id = '{$story_id}'
					AND user_id='{$uid}'
			";
			$query = $this->db->query( $sql );
			$num = $query->row()->flag;
			
			$cur_date = date('Y-m-d H:i:s');
			if( $num == 0 ) {
				$sql = "INSERT INTO history( story_id, user_id, record_date) VALUES ('{$story_id}','{$uid}','{$cur_date}')";
				$this->db->query( $sql );
			} else {
				$sql = "UPDATE history SET record_date='{$cur_date}' WHERE story_id = '{$story_id}'";
				$this->db->query( $sql );
			}
		}
		
		function del_story( $story_id ) {
			// 删除故事
			$sql = "
				DELETE FROM story
				WHERE story_id = '{$story_id}'
			";
			$this->db->query( $sql );
			
			$sql = "
				DELETE FROM comment
				WHERE story_id = '{$story_id}'
			";
			$this->db->query( $sql );
			
			$sql = "
				DELETE FROM feeds
				WHERE story_id = '{$story_id}'
			";
			$this->db->query( $sql );
			
			$sql = "
				DELETE FROM vote
				WHERE story_id = '{$story_id}'
			";
			$this->db->query( $sql );
		}
		
		
		function html_user_short_profile( $author_id, $uid = -1) {	// tbe
			// 打印200个像素的用户头像
			// author_id 查看的作者编号
			// uid 当前登录的用户编号
			
			$x = $this->User_model->user_profile( $author_id );
			$author = $x['row'];
			extract( $author );
			$author_photo = UVIEW_PATH.$user_photo;
			$profile_link = HOSTURL.'user/?id='.$author_id;
			$gname = "";
			switch( $gender ) {
				case 0: 
					$gname = "保密";
					
					break;
				case 1: 
					$gname = "男";
					$gimg = UVIEW_PATH.'male.png';
					$gcls = "male";
					break;
				case 2: 
					$gname = "女";
					$gimg = UVIEW_PATH.'female.png';
					$gcls = "female";
					break;
			}
			
			$birthday = substr( $birthday, 0 , 10 );
			$x = $this->User_model->user_statis($author_id, 2);
			$num = $x['num'];
			$link = HOSTURL."user/archive?id=".$author_id;
	?>
		<div class="attach-wrap">
			<div class="title"><span>作者信息<i style="color: #66BC4E;">/&nbsp;writer</i></span></div>
			<div class="attach-box">
				<div class="attach-img">
					<div class="img"><a href="<?=$profile_link?>" target="_blank"><img src="<?=$author_photo?>" width="80px" height="80px" class="img-rounded"/></a></div>
					<div class="desc reddit-desc">
						<h3><a href="<?=$profile_link?>" target="_blank"><?=$user_nickname?></a>
							<?php 
								if( $gender ) {
							?>
							<img src="<?=$gimg?>" width="20px"/>
							
							<?php
								}
							?>
						</h3>
						<p><?=$user_desc?></p>
					</div>
				</div>
				<div class="attach-info user-box">
					<div class="short-profile">
						
						<ul>
							<?php 
								if( $birthday !== "0000-00-00") {
							?>
							<li><label>生日: </label><span><?=$birthday?></span></li>
							<?php
								}
							?>
							<li><label>发表作品: </label><span><a href="<?=$profile_link?>" target="_blank"><?=$num?>篇</span></a></li>
						</ul>
					</div>
				
					<?php if( $uid != -1 ) {?>
					<div class="user-action">
						<?php
						$this->User_model->html_interact_with_user( $uid, $author_id );
						?>
					</div>
					<?php }?>
				</div>
			</div>
		</div>
	<?php
		}
		
		function html_short_column( $cid, $uid=-1 ) {
			$x = $this->Column_model->get_column( $cid );
			$column = $x['row'];
			extract( $column );
			$topic_icon = CVIEW_PATH.$topic_icon;
			$link = HOSTURL."column/?id=".$cid;
			$num = $this->Column_model->num_column_stories( $cid );
			$date = substr( $topic_create_date, 0 ,16 );
		?>
			<div class="attach-wrap">
				<div class="title"><span>专栏信息<i  style="color: #8C0000;">/&nbsp;column</i></span></div>
				<div class="attach-box">
					<div class="attach-img">
						<div class="img"><a href="<?=$link?>" target="_blank"><img src="<?=$topic_icon?>" width="80px" height="80px" class="img-rounded"/></a></div>
						<div class="desc reddit-desc">
							<h3><a href="<?=$link?>" target="_blank"><?=$topic_title?></a></h3>
							<p><?=$topic_desc?></p>
						</div>
					</div>
					<div class="attach-info user-box">
						<div class="short-profile">
							<ul>
								<li><label>创建时间: </label><span><?=$date?></span></li>
								<li><label>发表作品: </label><span><a href="<?=$link?>" target="_blank"><?=$num?>篇</span></a></li>
							</ul>
						</div>
					
						<?php if( $uid != -1 ) {?>
						<div class="user-action">
							<?php
							$this->Column_model->html_interact_with_column( $uid, $cid );
							?>
						</div>
						<?php }?>
					</div>
				</div>
			</div>
		<?php
	}
	
	function html_story_interact( $story_id, $uid, $author_id) {
		$comment_num = $this->get_story_comment_num( $story_id );
		$likes_num = $this->get_likes_num( $story_id );
		$unlikes_num = $this->get_likes_num( $story_id, 2 );
		$vote_status = $this->check_user_vote_status( $uid, $story_id );
		$mark1 = 0;
		$mark2 = 0;
		switch( $vote_status ) {
			case 1:
				$mark1 = 1;
				break;
			case 2:
				$mark2 =1;
				break;
		}
		$edit_link = HOSTURL.'home/write?act=1&id='.$story_id;
	?>
	<div class="bding-interact">
		<div class="interact-ways">
			<div class="left">
				<ul>
					<?php
					if( $uid !== -1 ) {
					?>
					<li><a href="javascript:void(0);" id="like-story-<?=$story_id?>" action="like-story" rel="<?=$story_id?>" data="1" marked="<?=$mark1?>"><span class="glyphicon glyphicon-thumbs-up"></span><span id="likes-sta-<?=$story_id?>">(<?=$likes_num?>)</span></a></li>
					<li><a href="javascript:void(0);" id="unlike-story-<?=$story_id?>" action="unlike-story" rel="<?=$story_id?>" data="2" marked="<?=$mark2?>"><span class="glyphicon glyphicon-thumbs-down"></span><span id="unlikes-sta-<?=$story_id?>">(<?=$unlikes_num?>)</span></a></li>
					<?php
					}
					?>
					<li><a href="javascript:void(0);" action="" title="侵权, 剽窃, 纯色情内容请举报"><i class='glyphicon glyphicon-bullhorn' style='margin-right: 5px;'></i>举报</a></li>
				</ul>
			</div>
			
			<div class="right">
				<ul>
					<?php
						if( $uid == $author_id ) {
							echo "<li><a href='{$edit_link}'><i class='glyphicon glyphicon-edit' style='margin-right: 5px;'></i>编辑</a></li>";
							echo "<li><a href='javascript:void(0);' action='del-bding' rel='{$story_id}'><i class='glyphicon glyphicon-remove-sign' style='margin-right: 5px;'></i>删除</a></li>";
						}
					?>
					<?php
					if( $uid !== -1 ) {
					?>
					<li><a href="javascript:void(0);" rel="<?=$story_id?>" action="expand-comment"><i class='glyphicon glyphicon-comment' style='margin-right: 5px;'></i>评论<span style="font-size: 13px;" id="sta-comment-<?=$story_id?>">(<?=$comment_num?>)<span></a></li>
					<li><a href="javascript:void(0);" action="collect-bding"><i class='glyphicon glyphicon-bookmark' style='margin-right: 5px;'></i>收藏</a></li>
					<?php
					}
					?>
					<li><a href="javascript:void(0);" action="share-bding"><i class='glyphicon glyphicon-share' style='margin-right: 5px;'></i>分享</a></li>
				</ul>
			</div>
		</div>
		
		<div class="bding-comment" id="comment-field-<?=$story_id?>">
			<div class="text-comment">
				<textarea></textarea>
				<div><a href="javascript:void(0);" class="post-comment-btn" action="post-comment" rel="<?=$story_id?>" cc="-1" to="<?=$author_id?>">贴上</a></div>
			</div>
			<?php
			$this->html_comment_list( 1, $story_id, $uid );
			?>
		</div>
	</div>
	
	<?php
	}
	
	function get_story_comments( $page, $story_id ) {
		$size = 20;
		$start = ($page - 1 ) * $size;
		
		$sql = "
			SELECT 
				user.user_id,
				user.user_nickname,
				user.user_photo,
				user.user_desc,
				comment.comment_id,
				comment.comment_date,
				comment.comment_content
			FROM comment, user
			WHERE comment.story_id = '{$story_id}'
				AND comment.user_id = user.user_id
			ORDER BY comment_date DESC
			LIMIT {$start}, {$size}
		";
		
		$query = $this->db->query( $sql );
		return $query->result_array();
	}
	
	function html_comment_switcher( $story_id ) {	
		// 评论开关
	?>
		<div class="comment-switcher">
			<ul>
				<li><a href="#">最新的</a>&nbsp;/</li>
				<li><a href="#">热门的</a>&nbsp;/</li>
				<li><a href="#">我关注的</a></li>
			</ul>
		</div>
	<?php
	}
	
	function html_comment_list( $page, $story_id, $uid ) {
		$comments = $this->get_story_comments( $page, $story_id );
		$comments_num = count( $comments );
	?>
		<div class="comment-list">
			<?php
			if( $comments_num > 0 ) {
				$this->html_comment_switcher( $story_id );
			}
			?>
			<div class="comment-item first-comment-item"></div>
			<?php
			if( $comments_num> 0 ) {
				foreach( $comments as $item ) {
					extract( $item );
					$user_photo = UVIEW_PATH.$user_photo;
					$comment_date = substr( $comment_date, 0, 16 );
					$user_link = HOSTURL.'user/?id='.$user_id;
					
				?>
				<div class="comment-item" id="comment-<?=$comment_id?>">
					<div class="photo">
						<a href="<?=$user_link?>" target="_blank"><img src="<?=$user_photo?>" width="25px" height="25px" class="img-circle"/></a>
					</div>
					
					<div class="content">
						<div class="record pull-right">
							<ul>
								<li class="date"><?=$comment_date?></li>
								<li class="name"><a href="<?=$user_link?>" target="_blank" title="<?=$user_desc?>"><?=$user_nickname?></a></li>
						
								<li class="act pull-right">
								<?php
								$this->html_comment_interact( $comment_id, $story_id, $uid, $user_id );
								?>
								</li>
							</ul>
						</div>
						
						<div class="say-words">
							<p><?=$comment_content?></p>
						</div>
					</div>
				</div>
				<?php
				}
			}
			?>
		</div>
		
	<?php
	}
	
	function html_comment_interact( $comment_id, $story_id, $uid, $cc ) {
		$vote_num = $this->get_comment_likes_num( $comment_id );
		
		$vote_status = "";
		$voted = $this->check_user_vote_status( $uid, $comment_id, 1 );
		if( $voted == 1 ) {
			$vote_status = "class='voted'";
		}
	?>
		<a href="javascript:void(0);" <?=$vote_status?> action="vote-comment" voted="<?=$voted?>" rel="<?=$comment_id?>"><i class="glyphicon glyphicon-thumbs-up" style="margin-right: 5px;"></i>(<span id="comment-vote-<?=$comment_id?>"><?=$vote_num?></span>)</a>
		<a href="javascript:void(0);" action="reply-comment" rel="<?=$comment_id?>" tar="<?=$story_id?>" cc="<?=$cc?>"><i class="glyphicon glyphicon-send" style="margin-right: 5px;"></i>回复</a>&nbsp;&nbsp;&nbsp;
		
	<?php
	}
	
	function get_user_max_comment_id( $uid ) {
		$sql = "
			SELECT MAX(comment_id) AS idx
			FROM comment
			WHERE user_id = '{$uid}'
		";
		
		$query = $this->db->query( $sql );
		return $query->row()->idx;
	}
	
	function post_comment( $story_id, $uid, $comment_content, $type = 0, $talk_with_id = 0 ) {
		$story_id = mysql_real_escape_string( trim( $story_id ) ) ;
		$uid = mysql_real_escape_string( trim( $uid ) ) ;
		$comment_content = mysql_real_escape_string( trim( $comment_content ) ) ;
		$type = mysql_real_escape_string( trim( $type ) ) ;
		$comment_date = date('Y-m-d H:i:s');
		
		$sql = "
			INSERT INTO
				comment( story_id, comment_date, comment_content, user_id, talk_with_id, type ) 
			VALUES
				('{$story_id}', '{$comment_date}', '{$comment_content}', '{$uid}', '{$talk_with_id}', '{$type}')
		";
	
		if( $this->db->query( $sql ) ) {
			$x = $this->User_model->user_profile( $uid );
			$item = $x['row'];
			extract( $item );
			$user_photo = UVIEW_PATH.$user_photo;
			$comment_date = substr( $comment_date, 0, 16 );
			$user_link = HOSTURL.'user/?id='.$user_id;
			if (!empty( $user_desc ) ) {
				$user_desc = '('.$user_desc.')';
			}
			$comment_id = $this->get_user_max_comment_id( $uid );
		?>
			<div class="comment-item">
					<div class="photo">
						<a href="<?=$user_link?>" target="_blank"><img src="<?=$user_photo?>" width="25px" height="25px"/></a>
					</div>
					
					<div class="content">
						<div class="record pull-right">
							<ul>
								<li class="date"><?=$comment_date?></li>
								<li class="name"><a href="<?=$user_link?>" target="_blank" title="<?=$user_desc?>"><?=$user_nickname?></a></li>
						
								<li class="act pull-right">
								<?php
								// $this->html_comment_interact( $comment_id, $story_id, $uid );
								?>
								</li>
							</ul>
						</div>
						
						<div class="say-words">
							<p><?=$comment_content?></p>
						</div>
					</div>
			</div>
		<?php
		}
	}
	
	function get_user_max_sid( $uid ) {
		$sql = "
			SELECT MAX(story_id) AS sid
			FROM story
			WHERE user_id = '{$uid}'
				AND story_type = '0' 
		";
		$query = $this->db->query( $sql );
		return $query->row()->sid;
	}
	
	function del_user_comment_vote( $comment_id, $uid ) {
		$sql = "
			DELETE	
			FROM vote
			WHERE
				story_id = '{$comment_id}'
				AND user_id = '{$uid}'
				AND vote_for = '1'
		";
		
		if( $this->db->query( $sql ) ) 
			return 1;
		return 0;
	}
	
	function get_max_comment_id( $story_id, $uid ) {
		$sql = "
			SELECT MAX(comment_id)	AS id
			FROM comment
			WHERE story_id = '{$story_id}'
				AND user_id='{$uid}'
		";
		$query = $this->db->query( $sql );
		return $query->row()->id;
	}
	
	function get_user_nickname( $uid ) {
		$sql = "
			SELECT user_nickname
			FROM user
			WHERE user_id='{$uid}'
		";
	
		$query = $this->db->query( $sql );
		return $query->row()->user_nickname;
	}
	
	function get_story_title( $story_id ) {
		$sql = "
			SELECT story_title
			FROM story
			WHERE story_id='{$story_id}'
		";
		$query = $this->db->query( $sql );
		return $query->row()->story_title;
	}
	
	function send_comment_notice( $comment_id, $uid, $story_id, $to ) {
		
		$user_nickname = $this->get_user_nickname( $uid );
		$user_link = HOSTURL."user?id={$uid}";
		$comment_from = "<a href='{$user_link}' target='_blank'>{$user_nickname}</a>";
		$story_title = $this->get_story_title( $story_id );
		$story_link = HOSTURL."home/reddit?id={$story_id}";
		$story_link = "<a href='{$story_link}' target='_blank'>{$story_title}</a>";
		
		
		
		
		$sql = "
			SELECT comment_content
			FROM comment
			WHERE comment_id = '{$comment_id}'
		";
		$query = $this->db->query( $sql );
		$comment_content = $query->row()->comment_content;
		$content = "{$comment_from}评价了故事{$story_link}:{$comment_content}";
		
		$content = addslashes( $content );
		$sent_date = date('Y-m-d H:i:s');
		$sql = "
			INSERT INTO 
				mail(sender, receiver, content, sent_date, type)
			VALUES
				('10002', '{$to}', '{$content}','{$sent_date}', '1')
		";
		$this->db->query( $sql );
	}
	
	
	
}
?>